<template>
  <div class="userManage">
    <el-form :inline="true" ref="searchForm" :model="searchForm" >
      <el-form-item class="block-line">
        <el-col :span="8">
          <el-autocomplete v-model="searchForm.wd"
          :trigger-on-focus="false"
          :fetch-suggestions="querySearchAsync"
          custom-item="my-item-zh"
          placeholder="用户名、真实姓名、手机号、邮箱"
          :icon="icon"
          :on-icon-click="handleIconClick"
          @select="handleSelect"
          @input="searchForm.uid=null"
          @keyup.enter.native="submitForm"
          style="width:100%"></el-autocomplete>
        </el-col>
        <el-col :span="3"><el-button type="primary" style="margin-left:10px" @click="searchForm.page = 1;submitForm()">搜索</el-button></el-col>
      </el-form-item>
      <el-form-item label="所属架构">
        <el-select placeholder="请选择" v-model="searchForm.groupId" clearable>
          <el-option v-for="item in groups" :key="item.gid" :label="item.gName" :value="item.gid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色">
        <el-select placeholder="请选择" v-model="searchForm.characterId" clearable>
          <el-option v-for="item in roles" :key="item.cid" :label="item.cName" :value="item.cid"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="账号状态">
        <el-select placeholder="请选择" v-model="searchForm.memberStatus" clearable>
          <el-option :value="1" label="正常"></el-option>
          <el-option :value="0" label="冻结"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div v-if="userInfo.characterId == 1 || userInfo.characterId == 2" class="tb-head">
      <router-link :to="{name:'AddUser'}"><el-button icon="plus">新建用户</el-button></router-link>
    </div>
    <el-table
      v-loading="tbLoading"
      element-loading-text="拼命加载中"
      :data="users.list"
      stripe
      style="width: 100%"
      @sort-change="handleTableSort"
      class="table">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column label="头像/用户名" className="is-left" width="220px">
        <template slot-scope="scope">
          <img :src="getAvatar(scope.row.uid)" alt="" class="avatar">
          {{scope.row.username}}
          <el-tag v-if="character(scope.row.characterId)" type="primary" style="margin-top:5px">{{character(scope.row.characterId)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="realname" label="真实姓名" className="is-center">
      </el-table-column>
      <el-table-column prop="groupName" label="架构" className="is-center">
      </el-table-column>
      <el-table-column label="手机/邮箱" width="200px" className="is-center">
        <template slot-scope="scope">
          <div>{{scope.row.phone}}</div>
          <div>{{scope.row.email}}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="账号状态" className="is-center">
        <template slot-scope="scope">
          <div v-if="scope.row.status==1">正常</div>
          <div v-else>冻结</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="120px" className="is-center" sortable="custom">
        <template slot-scope="scope">
          {{dateFormat(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" className="is-center">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="$router.push({name: 'EditUser', params: {uid: scope.row.uid}})">查看</el-button>
          <el-button
            size="small"
            v-if="scope.row.status==1"
            type="text"
            @click="handleFreeze(scope.row.uid)"
            :disabled="!scope.row.freeze"
            class="red">冻结</el-button>
          <el-button
            size="small"
            v-else type="text"
            :disabled="!scope.row.freeze"
            @click="handleUnfreeze(scope.row.uid)"
            class="red">解冻</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        :current-page.sync="searchForm.page"
        :page-size.sync="searchForm.size"
        layout="sizes, total, prev, pager, next, jumper"
        :total="users.page.total"
        :page-sizes="[10, 50, 100]"
        @current-change="submitForm('searchForm')"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import {mapState, mapActions} from 'vuex'
  import env from '@/config/env'
  // el-autoComplete 提示自定义样式
  Vue.component('my-item-zh', {
    functional: true,
    render: function (h, ctx) {
      let item = ctx.props.item
      let wd = ctx.parent.$parent.value
      let target = ''
      for (let key in item.value) {
        if (item.value[key].toString().indexOf(wd) !== -1) {
          target = item.value[key]
          break
        }
      }
      let reg = new RegExp('(.*)' + wd + '(.*)')
      reg.exec(target)
      let left = RegExp.$1
      let right = RegExp.$2
      return h('li', ctx.data, [
        h('span', { attrs: { class: 'name' } }, [item.value.realName]),
        h('span', { attrs: { class: 'left' } }, ['(', left]),
        h('span', { attrs: { class: 'highLight' } }, [wd]),
        h('span', { attrs: { class: 'right' } }, [right, ')'])
      ])
    },
    props: {
      item: { type: Object, required: true }
    }
  })
  export default{
    data () {
      return {
        searchForm: {
          wd: this.$route.params.wd || '',
          uid: '',
          groupId: this.$route.params.gid || '',
          characterId: this.$route.params.cid || '',
          page: 1,
          size: 10,
          memberStatus: null
        },
        icon: null,
        tbLoading: true
      }
    },
    mounted () {
      this.initTable()
      this.getGroupList()
      this.getRoleList()
    },
    computed: {
      ...mapState({
        users: state => state.sysManage.users,
        groups: state => state.sysManage.groups,
        roles: state => state.sysManage.roles,
        autoComplete: state => state.sysManage.autoComplete,
        userInfo: state => state.userInfo
      }),
      autoComArray () {
        var result = []
        if (this.autoComplete) {
          this.autoComplete.forEach(child => {
            result.push({value: child})
          })
        }
        return result
      }
    },
    methods: {
      ...mapActions(['getUserList', 'getGroupList', 'getRoleList', 'getAutoComplete', 'freezeUser', 'unfreezeUser']),
      initTable () {
        this.submitForm()
      },
      // 日期格式化
      dateFormat (date) {
        return this.$date.format(new Date(date), 'YYYY-MM-DD HH:mm:ss')
      },
      // 查询autocomplete
      querySearchAsync (queryString, cb) {
        this.getAutoComplete({wd: queryString, size: 5})
          .then(() => {
            let result = this.autoComArray.filter(this.createStateFilter(queryString))
            // console.log(result)
            let tempArr = []
            result.map((item) => {
              let userMobile = item.value.phone ? item.value.phone : '无'
              let userEmail = item.value.email ? item.value.phone : '无'
              tempArr.push({
                value: item.value.realName + '(手机号：' + userMobile + '， 邮箱：'+ userEmail +')', // 查询匹配结果
                uid: item.value.uid,
                realName: item.value.realName
              })
            })
            cb(tempArr)
            //cb(this.autoComArray)
          })
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.realName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      // 选择autocomplete选项
      handleSelect (item) {
      	// console.log(item)
        this.icon = 'circle-close'
        this.searchForm.uid = item.uid
        this.searchForm.wd = item.realName
        this.submitForm()
      },
      // 提交
      submitForm () {
        this.getUserList({...this.searchForm})
          .finally((res) => { this.tbLoading = false })
      },
      // 删除搜索输入框内容
      handleIconClick () {
        this.icon = ''
        this.searchForm.wd = ''
        this.searchForm.uid = null
      },
      // 更改每页条数
      handleSizeChange (size) {
        this.searchForm.size = size
        this.submitForm()
      },
      // 冻结用户
      handleFreeze (uid) {
        this.$confirm('是否确认冻结用户？', '冻结用户')
          .then(() => {
            return this.freezeUser(uid)
          })
          .then(res => {
            this.initTable()
            this.$message({
              type: 'success',
              message: res.data.msgZ
            })
          })
      },
      // 解冻用户
      handleUnfreeze (uid) {
        this.$confirm('是否确认解冻用户？', '解冻用户')
          .then(() => {
            return this.unfreezeUser(uid)
          })
          .then(res => {
            this.initTable()
            this.$message({
              type: 'success',
              message: res.data.msgZ
            })
          })
      },
      handleTableSort (type) {
        if (type.order === 'descending') {
          this.searchForm.timeSort = 0
        } else {
          this.searchForm.timeSort = 1
        }
        this.submitForm()
      },
      // 获取头像
      getAvatar (uid) {
        return `${env.baseUrl}/sys/member/avatar/s/${uid}?${Math.random()}`
      },
      // 获取角色名
      character (id) {
        if (id === 1 || id === 2) {
          return '管理员'
        } else if (id === 3) {
          return '品牌vi'
        }
      }
    }
  }
</script>
<style lang="scss">
  .userManage{
    .block-line{display:block;width:100%;}
    .block-line .el-form-item__content{display: block;}
    .avatar{float:left;margin-right:3px;width:32px;height:32px;border-radius:50%;vertical-align:middle;}
    .name_wrap{margin-left:35px}
    .pagination{margin-top:16px;}
    .el-pagination{text-align:right;}
    .el-pagination__sizes{float:left;}
    .el-dropdown-menu{width:180px}
  }
  .UM-dropdown{width:140px}
  .el-autocomplete-suggestion{
    .highLight{color:red}
    .left{margin-left:15px;}
  }
</style>
